package com.hw.hcit.feature;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.graphics.RectF;
import android.hardware.Camera;
import android.hardware.Camera.AutoFocusCallback;
import android.hardware.Camera.CameraInfo;
import android.hardware.Camera.Parameters;
import android.os.BatteryManager;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.hw.hcit.conf.Config;
import com.hw.hcit.conf.DrawCaptureRect;
import com.hw.hcit.conf.JTestItem;
import com.hw.hcit.R;

public class FrontCameraTestItem extends JTestItem implements OnClickListener, AutoFocusCallback
{
    private final static String TAG = "FrontCameraTestItem"; 
    private SurfaceView mSurfaceView;
    private RelativeLayout mRelativeLayout;
    private SurfaceHolder mSurfaceHolder;
    private Camera camera; 
    private DrawCaptureRect mDrawCaptureRect;
    private boolean mCanpass = false;
    private boolean powerClicked = false;
    private Button successButton,failButton;
    private int mBackCameraId = -1;
    private int mFrontCameraId = -1;
    private  CameraInfo[] mInfo;
    private  static int mNumberOfCameras;
    
    public FrontCameraTestItem() {
        super();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) 
    {
        View rootView = inflater.inflate(R.layout.backcamera_test, container, false);
        mSurfaceView = (SurfaceView) rootView.findViewById(R.id.camera_preview);
        mRelativeLayout = (RelativeLayout) rootView.findViewById(R.id.backcamera_layout);
        /*15-10-15 gaoshenpan fix judge camera exit begin */
        if(hasFrontFacingCamera()){
        setupViews();  
        }else{
        configDialog();    
        }
        /*15-10-15 gaoshenpan fix judge camera exit end */
        return rootView;
    }
    /*15-10-15 gaoshenpan add dialog for camera not exit begin */
    public void configDialog(){
        AlertDialog.Builder builder = new AlertDialog.Builder(Config.GetActivity());
        builder.setTitle(getString(R.string.camera_wrong))
               .setMessage(getString(R.string.check_frontcamera))
               .setCancelable(false)
               .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
                   public void onClick(DialogInterface dialog, int id) {
                               dialog.cancel();
                             Config.GetActivity().getFragmentManager().beginTransaction()
                               .replace(R.id.frame_layout, Config.PROJECTS.getUI()).commit();
                   }
               });
        AlertDialog alert = builder.create();
        alert.show();
    }
    /*15-10-15 gaoshenpan add dialog for camera not exit end */
    private void setupViews() {
        mSurfaceHolder = mSurfaceView.getHolder();
        mSurfaceHolder.addCallback(surfaceCallback);
        mSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
    } 
    
//    public void drawFocus(SurfaceHolder holder) {
//        Paint focusPaint = new Paint();
//        focusPaint.setAntiAlias(true);
//        focusPaint.setColor(Color.WHITE);
//        focusPaint.setStyle(Paint.Style.STROKE);
//        focusPaint.setStrokeWidth(3);
//        Canvas canvas = holder.lockCanvas();
//        canvas.drawRect(mSurfaceView.getWidth()/2-60, mSurfaceView.getHeight()/2-60, mSurfaceView.getWidth()/2+60, mSurfaceView.getHeight()/2+60, focusPaint);
//        holder.unlockCanvasAndPost(canvas);
//        Log.d(TAG, "drawFocus    ====");
//    }
    
    SurfaceHolder.Callback surfaceCallback = new SurfaceHolder.Callback() {  
          
        public void surfaceCreated(SurfaceHolder holder) {  
            Log.i(TAG, "surfaceCallback===="); 
            camera = Camera.open(mNumberOfCameras == 1 ? 0 :1); 
            try {  
                camera.setPreviewDisplay(holder); 
            } catch (IOException e) {  
                camera.release();
                camera = null;  
            }  
            
            RelativeLayout.LayoutParams layoutParams   =new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
            layoutParams.setMargins(mSurfaceView.getWidth()/2-350, mSurfaceView.getHeight()/2+300, mSurfaceView.getWidth()/2-50, mSurfaceView.getHeight()/2+600);
            
            RelativeLayout.LayoutParams layoutParams1   =new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
            layoutParams1.setMargins(mSurfaceView.getWidth()/2+50, mSurfaceView.getHeight()/2+300, mSurfaceView.getWidth()/2+350, mSurfaceView.getHeight()/2+600);

            successButton = new Button(Config.GetActivity());
            failButton = new Button(Config.GetActivity());
            
            successButton.setWidth(300);
            successButton.setHeight(200);
            successButton.setAlpha(0.5f);
            successButton.setTextColor(Color.GREEN);
            successButton.setText(getString(R.string.success));
            successButton.setOnClickListener(new OnClickListener() {
                
                @Override
                public void onClick(View arg0) {
                    // TODO Auto-generated method stub
                    Log.d(TAG, "successButton.setOnClickListener"+"onclick");
                    if(Config.CURR_PROJECT.isAuto()){
                        if (!Config.ageingTested) {
                            rewriteOneByteOfNv2499(9, 'P');
                        } else {
                            rewriteOneByteOfNv2499(40, 'P');
                        }
                    }
                    testFinish(true, 1, true);
                }
            });
            
            failButton.setWidth(300);
            failButton.setHeight(200);
            failButton.setAlpha(0.5f);
            failButton.setTextColor(Color.GREEN);
            failButton.setText(getString(R.string.fail));
            failButton.setOnClickListener(new OnClickListener() {
                
                @Override
                public void onClick(View arg0) {
                    // TODO Auto-generated method stub
                    Log.d(TAG, "failButton.setOnClickListener"+"onclick");
                    if(Config.CURR_PROJECT.isAuto()){
                        if (!Config.ageingTested) {
                            rewriteOneByteOfNv2499(9, 'F');
                        } else {
                            rewriteOneByteOfNv2499(40, 'F');
                        }
                    }
                    testFinish(false, 1, false);
                }
            });
            
            mRelativeLayout.addView(successButton,layoutParams);
            mRelativeLayout.addView(failButton,layoutParams1);
//            mDrawCaptureRect = new DrawCaptureRect(Config.GetActivity(),mSurfaceView.getWidth()/2-100, mSurfaceView.getHeight()/2-100,
//                    200, 200, Color.RED);
//            mRelativeLayout.addView(mDrawCaptureRect, new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
        }  
  
        public void surfaceChanged(SurfaceHolder holder, int format, int width,  
                int height) {  
            Log.i(TAG,"====surfaceChanged");  
            
            Camera.Parameters parameters = camera.getParameters(); 
            parameters.setPreviewSize(1280, 720);
            parameters.setFocusMode(Parameters.FOCUS_MODE_AUTO);
//            parameters.setTouchAfAec(Parameters.TOUCH_AF_AEC_ON);
            parameters.setPictureFormat(PixelFormat.JPEG); 
            camera.setDisplayOrientation(90);  
            camera.setParameters(parameters); 
            camera.startPreview();
        }  
  
        public void surfaceDestroyed(SurfaceHolder holder) {  
            Log.i(TAG,"====surfaceDestroyed");  
            camera.stopPreview(); 
            camera.release(); 
            camera = null;  
        }  
    };  
    
    public void onTouchEvent(MotionEvent event) {
        Log.d(TAG, "onTouchEvent");
//        mRelativeLayout.removeView(mDrawCaptureRect);
//        mDrawCaptureRect.setColor(Color.GREEN);
//        mRelativeLayout.addView(mDrawCaptureRect, new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
        /*15-11-14 gaoshenpan fix too much touchEvent caused jni exception crash begin*/
        try {
            focusOnTouch(event);
        } catch (Exception e) {
            // TODO: handle exception
             Log.d(TAG, "too many touches onTouchEvent");
             e.printStackTrace();
        }
        /*15-11-14 gaoshenpan fix too much touchEvent caused jni exception crash end*/
    };
    
    public void focusOnTouch(MotionEvent event) {  
        Rect focusRect = calculateTapArea(event.getRawX(), event.getRawY(), 1f);  
        Rect meteringRect = calculateTapArea(event.getRawX(), event.getRawY(), 1f);  
  
        Camera.Parameters parameters = camera.getParameters();  
        parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO);  
          
        if (parameters.getMaxNumFocusAreas() > 0) {  
            List<Camera.Area> focusAreas = new ArrayList<Camera.Area>();  
            focusAreas.add(new Camera.Area(focusRect, 1));  
          
            parameters.setFocusAreas(focusAreas);  
            Log.d(TAG, "focusRect="+focusRect.width());
            Log.d(TAG, "focusRect="+focusRect.height());
        }  
  
        if (parameters.getMaxNumMeteringAreas() > 0) {  
            List<Camera.Area> meteringAreas = new ArrayList<Camera.Area>();  
            meteringAreas.add(new Camera.Area(meteringRect, 1));  
              
            parameters.setMeteringAreas(meteringAreas);  
            Log.d(TAG, "meteringRect="+meteringRect.width());
            Log.d(TAG, "meteringRect="+meteringRect.height());
        }  
  
        camera.setParameters(parameters);  
        camera.autoFocus(this);  
    }  
    
    public Camera.Size getResolution() {  
        Camera.Parameters params = camera.getParameters();   
        Camera.Size s = params.getPreviewSize();  
        return s;  
    }  
    
    private Rect calculateTapArea(float x, float y, float coefficient) {  
        float focusAreaSize = 300;  
        int areaSize = Float.valueOf(focusAreaSize * coefficient).intValue();  
  
        int centerX = (int) (x / getResolution().height * 2000 - 1000);  
        int centerY = (int) (y / getResolution().width * 2000 - 1000);  
  
        int left = clamp(centerX - areaSize / 2, -1000, 1000);  
        int right = clamp(left + areaSize, -1000, 1000);  
        int top = clamp(centerY - areaSize / 2, -1000, 1000);  
        int bottom = clamp(top + areaSize, -1000, 1000); 
        Log.d(TAG, "calculateTapArea========"+"   getResolution().width="+getResolution().width);
        Log.d(TAG, "calculateTapArea========"+"   getResolution().height="+getResolution().height);
        Log.d(TAG, "calculateTapArea========"+"   x="+x+"   y="+y);
        Log.d(TAG, "calculateTapArea========"+"   centerX="+centerX+"   centerY="+centerY);
        Log.d(TAG, "calculateTapArea========"+"   left="+left+"   right="+right+"   top="+top+"   bottom="+bottom);
  
        return new Rect(left, top, right, bottom);  
    }  
    
    private int clamp(int x, int min, int max) {  
        if (x > max) {  
            return max;  
        }  
        if (x < min) {  
            return min;  
        }  
        return x;  
    }  
   
    @Override
    public boolean getResult() {
        // TODO Auto-generated method stub
        return false;
    }

    @Override
    public String getResultInfo() {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public void startTest() {
        // TODO Auto-generated method stub

    }

    @Override
    public void stopTest() {
        // TODO Auto-generated method stub
        
    }

    @Override
    public void refresh()
    {
        
    }

    
    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        //nv write
        //Config.curr_pro.isAuto()
        //Config.curr_pro.getType()
        //Config.CURR_PROJECT.getType()
    }

    @Override
    public void onAutoFocus(boolean success, Camera camera) {
        // TODO Auto-generated method stub
        if (success) {
            mCanpass = true;
        }
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        // TODO Auto-generated method stub
        return true;
    }
    /*@Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        // TODO Auto-generated method stub
        if (event.getKeyCode() == KeyEvent.KEYCODE_VOLUME_DOWN) {
            dissmissPowerClicked();
            Log.d(TAG, " --------->KeyEvent.KEYCODE_VOLUME_DOWN");
            if (powerClicked) {
                Log.d(TAG,
                        "powerClicked --------->KeyEvent.KEYCODE_VOLUME_DOWN");
                if(Config.CURR_PROJECT.isAuto()){
                    if (!Config.ageingTested) {
                        rewriteOneByteOfNv2499(37, 'F');
                    } else {
                        rewriteOneByteOfNv2499(66, 'F');
                    }
                }
                testFinish(false, 1, false);
                return true;
            }
            Log.d(TAG, "tested --------->KeyEvent.KEYCODE_VOLUME_DOWN");
            if(Config.CURR_PROJECT.isAuto()){
                if (!Config.ageingTested) {
                    rewriteOneByteOfNv2499(37, 'P');
                } else {
                    rewriteOneByteOfNv2499(66, 'P');
                }
            }
            testFinish(true, 1, true);
        } else if (event.getKeyCode() == KeyEvent.KEYCODE_VOLUME_UP) {
            dissmissPowerClicked();
            testFinish(true, -1, true);
        } else if (event.getKeyCode() == KeyEvent.KEYCODE_POWER) {
            Log.d(TAG, "powerClicked --------->KeyEvent.KEYCODE_POWER");
            powerClicked = true;
            showPowerClicked();
        }
        return true;
    }*/
    /*15-10-15 gaoshenpan fix judge camera exit begin */
    private static boolean checkCameraFacing(final int facing) {
        mNumberOfCameras = Camera.getNumberOfCameras();
        CameraInfo info = new CameraInfo();
        Log.d(TAG, "cameraCount------>"+mNumberOfCameras);
        for (int i = 0; i < mNumberOfCameras; i++) {
            Camera.getCameraInfo(i, info);
            Log.d(TAG, "i------>"+i+"\n"+
                    "info.facing="+info.facing);
            if (facing == info.facing) {
                return true;
            }
        }
        return false;
    }
    public static boolean hasBackFacingCamera() {
        final int CAMERA_FACING_BACK = 0;
        return checkCameraFacing(CAMERA_FACING_BACK);
    }
    public static boolean hasFrontFacingCamera() {
        final int CAMERA_FACING_BACK = 1;
        return checkCameraFacing(CAMERA_FACING_BACK);
    }
    public static int getSdkVersion() {
        return android.os.Build.VERSION.SDK_INT;
    }
    
    /*15-10-15 gaoshenpan fix judge camera exit end */
}
